import React, { Component } from 'react';
import {
	StyleSheet, Text, View, FlatList, Image, ActivityIndicator, ScrollView
} from "react-native";
import { BoxShadow } from 'react-native-shadow';

import navigationSeevice from '../../../../../components/navigation/navigationSeevice';
import Dictionary from '../../../../../utils/dictionary';
import { style } from '../../../../../theme/style';
import HTTP from '../../../../../utils/http';
import { API, API_GENERATE } from '../../../../../config/api';
import { CreditTabs, CreditFilterTabs } from './_components/Tabs';
import { CreditInfoSection } from './_components/CreditInfoSection';
import { CreditHistoryItem } from './_components/CreditHistoryItem';
import { StatusModel } from '../../../../../component/Store';
import { ScrollTabView } from '../../../../../component/ScrollTabView';
import { PageStatusIndex } from '../../../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;
const prohibitSource = require('../../../../../imgs/customer/prohibit.png');
const emptyPic = require('../../../../../imgs/global/dealtWithEmpty.png');
export class EnCreditComponent extends Component {
	static navigationOptions = {
		header: null
	}

	constructor(props) {
		super(props);
		this.currentCreditType = this.props.currentCreditType || null;
		this.creditApplyStatus = this.props.creditApplyStatus || null;
		this._closeLightBox = this._closeLightBox.bind(this);
		this.stateLightBoxData = {
			onClosePress: this._closeLightBox,
			modalVisible: false,
			title: '',
			rowDataList: [],
			status: 'loading'
		};

		this.state = {
			currentCreditType: this.currentCreditType || 1,  //1是预付，2是赊销
			stickList: [0],  //设置滚动时固定的视图
		}
	}

	async	componentWillMount () {
		this._init();
	}

	componentWillUnmount () {

	}

	//初始函数
	_init = async () => {
		const { data, choice } = this.props;
		const { companyInfoVO } = data;
		const { corpTypeList } = companyInfoVO || {};
		this.setState({
			upLoaded: true,
			loaded: true
		})
		//审批类型
		let creditFitlerTypes = await Dictionary.get('FIN_APP_CREDIT_APPLY_STATUS');
		//授信信息
		const standBook = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_CREDIT_DETAIL), {
			companyId: companyInfoVO.companyId,
			corpId: choice.corpId
		});
		//取出对应的赊销/预付信息
		const standBookState = {};
		standBook && standBook.length && standBook.map((item, index) => {
			standBookState[item.companyType] = item;
		})
		this.setState({
			upLoaded: false,
			standBookState,
			creditFitlerTypes
		}, () => this.getCreditHistory(companyInfoVO.companyId, this.currentCreditType || (corpTypeList && corpTypeList[0]) || this.state.currentCreditType, this.creditApplyStatus || ''));
	}

	async getCreditHistory (companyId, companyType, creditApplyStatus) {
		const creditList = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_CREDIT_HISTORY), {
			companyId,
			companyType,
			creditApplyStatus,
			corpId: this.props.choice.corpId
		});

		this.setState({
			loaded: false,
			creditList,
			currentCreditType: Number(companyType),
			creditApplyStatus
		})
	}

	_closeLightBox () {
		this.stateLightBoxData.modalVisible = false;
		const { stateLightBoxVisible } = this.state;
		this.setState({
			stateLightBoxVisible: !stateLightBoxVisible,
		});
	}

	//获取授信审批节点
	async	didPressShowStateLightBox (creditApplyId, processInstanceId) {
		let { choice } = this.props || {};
		//查询审批节点
		let stateInfo = await HTTP.GET(API_GENERATE(API.FIND_NODE), {
			processInstanceId,
			bizId: creditApplyId,
			bizObjType: '11',
			corpId: choice.corpId || null
		});

		this.stateLightBoxData.modalVisible = true;
		this.stateLightBoxData.title = '审批状态';
		this.stateLightBoxData.rowDataList = stateInfo && stateInfo.map((item, index) => {
			return {
				taskName: item.taskName,
				auditTime: item.auditTime,
				auditResult: item.auditResult,
				remark: item.remark,
				logId: item.logId,
				auditStaffName: item.auditStaffName
			};
		})

		const { stateLightBoxVisible } = this.state;
		this.setState({
			stateLightBoxVisible: !stateLightBoxVisible
		});
	}

	//授信渲染
	renderCompanyStandBookData () {
		const { ifEdit, data } = this.props;
		const { standBookState, currentCreditType, creditList, creditFitlerTypes, creditApplyStatus, stickList } = this.state;
		const currCredit = standBookState && standBookState[currentCreditType] ? standBookState[currentCreditType] : null;
		return (
			<View style={styles.standBookView}>
				{/*stickyHeaderIndices 固定第一个视图**/}
				<ScrollView stickyHeaderIndices={[0]} onScroll={(e) => {
					let offsetY = e.nativeEvent.contentOffset.y; //滑动距离
				}}>
					<CreditTabs ifEdit={ifEdit} corpTypeList={data.companyInfoVO.corpTypeList} currentCreditType={currentCreditType} onTextPress={() => {
						navigationSeevice.navigate('CreditFormPage', {
							goBack: 'EnterpriseDetailsPage',
							companyId: data.companyInfoVO.companyId || '',
							orderType: currentCreditType == 1 ? 'P' : 'S',
							choice: this.props.choice
						})
					}} onPress={(key) => {
						this.setState({ currentCreditType: key });
						this.getCreditHistory(data.companyInfoVO.companyId, key, creditApplyStatus);
					}} />

					<CreditInfoSection data={currCredit} upLoaded={this.state.upLoaded} loaded={this.state.loaded} currentCreditType={currentCreditType} onDetailPress={() => {
						navigationSeevice.navigate('CreditDetailPage', {
							title: '授信-' + (currentCreditType === 1 ? '预付' : '赊销'),
							companyName: data.companyInfoVO.companyName,
							creditInfo: currCredit
						})
					}} onBillPress={() => {
						navigationSeevice.navigate('BillPage', {
							goBack: 'EnterpriseDetailsPage',
							companyId: data.companyInfoVO.companyId,
							companyName: data.companyInfoVO.companyName,
							corpType: currentCreditType === 1 ? 1 : 0
						})
					}} />

					{
						creditFitlerTypes && creditFitlerTypes.length ?
							<CreditFilterTabs creditFitlerTypes={creditFitlerTypes} creditApplyStatus={creditApplyStatus}
								onPress={(type) => {
									this.setState({ creditApplyStatus: type });
									this.getCreditHistory(data.companyInfoVO.companyId, currentCreditType, type);
								}} /> : null
					}


					<View style={{ top: 0 }}>
						{
							creditList && creditList.length ?
								<FlatList
									data={creditList}
									renderItem={this.renderCreditHistoryItemView.bind(this)}
									onEndReachedThreshold={1}
									onRefresh={() => { this.getCreditHistory(data.companyInfoVO.companyId, currCredit.companyType, creditApplyStatus) }}
									refreshing={false}
								/>
								:
								<View style={{ alignItems: 'center' }}>
									{
										this.state.loaded ? null :
											<View>
												<Image source={emptyPic} style={styles.emptyPic} />
												<Text style={styles.emptyText}>暂无数据～</Text>
											</View>
									}
								</View>
						}
					</View>
				</ScrollView>
			</View >
		)
	}

	renderCreditHistoryItemView (creditHistory) {
		return (
			<CreditHistoryItem data={creditHistory.item} ifEdit={this.state.ifEdit}
				didPressState={(creditApplyId, processInstanceId) => this.didPressShowStateLightBox(creditApplyId, processInstanceId)}
				reApplyPress={() => {
					navigationSeevice.navigate('CreditFormPage', {
						echoData: creditHistory.item,
						orderType: creditHistory.item.creditKind === 'SX' ? 'S' : 'P',
					})
				}} />
		)
	}

	render () {
		const companyStandBookView = this.renderCompanyStandBookData();
		return (
			<View style={styles.contentHeight}>
				{companyStandBookView}
				<StatusModel  {...this.stateLightBoxData} textStyle={{ marginLeft: 15 * scale, marginRight: 5 * scale }} />
			</View>
		)
	}
}


const styles = StyleSheet.create({
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	emptyPic: {
		width: 143 * scale,
		height: 120 * scale,
	},
	emptyText: {
		marginTop: 16 * scale,
		fontSize: 13 * scale,
		color: '#4B4B4B'
	},
	standBookView: {
		// backgroundColor: style.color.bgGray,
		width: '100%'
	},
	contentHeight: {
		height: '100%',
		alignItems: 'center',
		// flex: 1
	},
})